<template>
    <BaseSheet
        v-model="showSheet"
        :title="t('')"
        :forceOpen="forceOpen"
        >
        <div class="flex flex-col justify-center items-center p-[1rem]" v-show="showEmailVerify">
            <BaseIcon name="uni-email" size="1.5rem" class="mb-[0.625rem]"/>
            <div>{{t('email_verify')}}</div>
            <div class="my-[1rem]">{{t('withdraw_email_verify_required')}}</div>
            <Form :validation-schema="emailSchema" @submit="submitEmail" class="w-full" v-slot="{ validate, meta }" ref="emailForm">
                <BaseInput required :label="t('contact_email_address')" :placeholder="t('input_email_placeholder')" name="email" class="mt-[1rem]">
                </BaseInput>
                <div class="font-[600] text-[0.75rem] mt-[0.875rem]" v-if="verifyType.phone">
                    <span>{{t('without_email')}}</span>
                    <span class="text-brand" @click="showEmailVerify = false">{{t('use_phone')}}</span>
                </div>
                <div class="w-full flex justify-center">
                    <BaseButton :loading="loadingEmailCheckRequest" class="text-text-white-3 my-[1.5rem] text-center text-[0.75rem]" @click="emailCheck(false, validate)" type="default" :disabled="isEmailCounting || !meta.valid">{{t('resend') + (isEmailCounting ? `${remaining}s` : '')}}</BaseButton>
                </div>
                <BaseButton class="w-full mt-[1rem] text-[.75rem]" html-type="submit" :loading="emailUpdating" :disabled="!meta.valid">{{t('save')}}</BaseButton>
            </Form>
        </div>
        <div class="flex flex-col justify-center items-center p-[1rem]" v-show="!showEmailVerify">
            <BaseIcon name="uni-phone" size="1.5rem" class="mb-[0.625rem]"/>
            <div>{{t('phone_verify')}}</div>
            <div class="my-[1rem]">{{t('withdraw_phone_verify_require')}}</div>
            <Form :validation-schema="phoneSchema" @submit="submitPhoneVerify" class="w-full" v-slot="{ meta, values, setFieldValue }" ref="phoneForm">
                <BaseInput required :label="t('phone_number')" :placeholder="t('input_phone_placeholder')" name="phone" class="mt-[1rem]" inputmode="numeric">
                    <template #left-icon>
                        <BaseDropdown position="right" @toggle="val => dropdownVisible = val">
                            <template v-slot:trigger>
                                <div class="flex border-r border-r-border-black-4 px-[0.5rem] w-[4.375rem] items-center">
                                <span class="mr-[0.25rem]">{{areaCodeOptionsFiltered.find(item => item.value === values.area)?.label}}</span>
                                <div :class="[dropdownVisible && 'rotate-180']" class="transition h-[0.75rem]">
                                    <BaseIcon name="uni-arrow-down" className="!text-text-white-2" size="size-[1.125rem]"/>
                                </div>
                                </div>
                            </template>
                            <template v-slot:menu>
                                <div @click="setFieldValue('area', item.value)" class="text-center py-[.375rem] w-[5rem]" v-for="item in areaCodeOptionsFiltered" :key="item.value">{{item.label}}</div>
                            </template>
                        </BaseDropdown>
                    </template>
                </BaseInput>
                <BaseInput required :label="t('change_password_verify_code')" :placeholder="t('input_code_placeholder')" name="code" class="mt-[1rem]" inputmode="numeric">
                </BaseInput>
                <div class="font-[600] text-[0.75rem] mt-[0.875rem]" v-if="verifyType.email">
                    <span>{{t('without_phone')}}</span>
                    <span class="text-brand" @click="showEmailVerify = true">{{t('use_email')}}</span>
                </div>
                <div class="w-full flex justify-center">
                    <BaseButton :loading="phoneCaptchaLoading" class="text-text-white-3 my-[1.5rem] text-center text-[0.75rem]" @click="sendCode" type="default" :disabled="isPhoneCounting">{{ hasSendPhoneCode ? t('resend') + (isPhoneCounting ? phoneCurrent.seconds + 's' : '') : t('send_sms_code')}}</BaseButton>
                </div>
                <BaseButton class="w-full mt-[1rem] text-[.75rem]" html-type="submit" :disabled="!meta.valid" :loading="phoneUpdateLoading">{{t('save')}}</BaseButton>
            </Form>
        </div>
    </BaseSheet>
</template>

<script lang="ts" setup>

const showSheet = ref(true)
const { t, locale } = useI18n();
import { useIntervalFn } from '@vueuse/core';
import { Form } from 'vee-validate';
import * as yup from 'yup';
const forceOpen = ref(true)
const appStore = useAppStore()
const { countryCallingCode } = useIpApi()
const dropdownVisible = ref(false)
const emailForm = ref()
const phoneForm = ref()
const hasSendPhoneCode = ref(false)

const emits = defineEmits(['update:modelValue', 'change', 'toggle'])
const { areaSearchValue, areaCodeOptionsFiltered, clearAreaSearchValue } = useAreaCode()
const { userInfo } = storeToRefs(useAppStore())
interface Props {
  position?: 'left' | 'center' | 'right'
  modelValue?: boolean
  verifyType: {
    phone: boolean
    email: boolean
  }
}
const props = withDefaults(defineProps<Props>(), {
  position: 'left',
  modelValue: false,
})
const showEmailVerify = ref(props.verifyType.email)

const emailSchema = yup.object().shape({
  email: yup.string().required(t('input_email_placeholder')).matches(emailReg, t('wrong_email_format')),
})

const phoneSchema = yup.object().shape({
  phone: yup.string().required(t('input_phone_placeholder')),
  code: yup.string().required(t('input_code_placeholder')),
  area: yup.string()
})

const total = 60
const remaining = ref(0)
const isEmailCounting = ref(false)
const isPhoneCounting = ref(false)
watch(() => userInfo.value?.email, (newValue?: string) => {
  emailForm.value?.setFieldValue('email', newValue ?? '')
}, {immediate: true})

onMounted(() => {
    emailForm.value?.setFieldValue('email', userInfo.value?.email ?? '')
    phoneForm.value?.setFieldValue('area', countryCallingCode.value)
})

watch(countryCallingCode, (a) => {
  phoneForm.value?.setFieldValue('area', a)
}, { immediate: true })

const {
  start: startPhoneCountdown,
  reset: resetPhoneCountdown,
  current: phoneCurrent,
} = useCountDown({
  time: 60 * 1000,
  onFinish() {
    isPhoneCounting.value = false
  },
})

/** 检测是否存在 */
const { runAsync: runExists } = useRequest(ApiMemberExists, {
  onSuccess(res) {
  },
  onError: () => {
    phoneForm.value.setFieldError('phone', t('phone_exists'))
  },
})

async function checkPhoneExit() {
    try{
        runExists({ ty: 3, val: `${phoneForm.value.values.area}-${phoneForm.value.values.phone}`, noNotify: true })
    }catch(e){
        console.log(e)
    }
}

/** 发送手机验证码 */
const {
  runAsync: runAsyncSendPhoneSms,
  loading: phoneCaptchaLoading,
} = useRequest(() => ApiMemberPhoneSms({ phone: `${phoneForm.value.values.area}-${phoneForm.value.values.phone}`, type: 0 }), {
  onSuccess() {
    hasSendPhoneCode.value = true
    resetPhoneCountdown()
    startPhoneCountdown()
    isPhoneCounting.value = true
    message.success(t('success_send_code'))
  },
})

defineOptions({
  name: 'AppWithdrawEmailOrPhoneVerify'
})

function submitEmail() {
    runMemberUpdate({ record: { email: emailForm.value.values.email }, uid: userInfo.value?.uid })
}
async function submitPhoneVerify(){
    await checkPhoneExit()
    if(phoneForm.value.meta.valid){
        runPhoneUpdate()
    }
}

const { runAsync: runMemberUpdate, loading: emailUpdating } = useRequest(ApiMemberUpdate, {
  onSuccess() {
    message.success('success')
    appStore.updateUserInfo()
    showSheet.value = false
  },
})
const {
  run: runEmailCheckRequest,
  loading: loadingEmailCheckRequest,
} = useRequest(ApiMemberEmailCheckRequest, {
  onSuccess() {
    message.success(t('success'))
    // showSheet.value = false
    resume()
    isEmailCounting.value = true
    remaining.value = total
  },
})

const { run: runPhoneUpdate, loading: phoneUpdateLoading } = useRequest(() => ApiMemberUpdate({
  record: {
    phone: `${phoneForm.value.values.area}-${phoneForm.value.values.phone}`,
  },
  uid: userInfo.value?.uid,
  captcha: phoneForm.value.values.code,
}), {
  async onSuccess() {
    await nextTick()
    message.success(t('phone_update_success'))
    showSheet.value = false
    nextTick(() => {
      appStore.updateUserInfo()
    })
  },
})

async function emailCheck(manual: boolean, validate: any) {
    const result = await validate()
    if(result.valid)
        runEmailCheckRequest({ email: emailForm.value.values.email })
}

// 倒计时逻辑
const { pause, resume } = useIntervalFn(() => {
  if (remaining.value > 0) {
    remaining.value--
  } else {
    pause()
    isEmailCounting.value = false
    resume()
  }
}, 1000, { immediate: false })

// 点击发送验证码
async function sendCode() {
    if (isPhoneCounting.value) return
    await checkPhoneExit()
    // 触发发送验证码逻辑（可加 API 调用
    const result = await phoneForm.value.validateField('phone')
    if(result.valid){
        await runAsyncSendPhoneSms()
        isPhoneCounting.value = true
    }
}

</script>
